<template>
  <div class="shb-chat-mask" v-show="show">
    <!-- 聊天窗口 -->
    <div v-show="!isZoomOutMode" class="shb-chat" v-loading="!isLoadEed" v-candrag="{
      bar: '.shb-chat-drag-header',
      target: '.shb-chat',
      mask: '.shb-chat-mask'
    }">

      <div class="header shb-chat-drag-header">
        <span class="title">{{ $t('common.base.onlineConsultation') }}</span>
        <div class="icon-box">
          <i class="iconfont icon-arrow-left" @click="redirect" v-if="showRedirect"></i>
          <i class="iconfont icon-zxh" @click="zoomHoverBall($event)"></i>
          <i class="iconfont icon-close" @click="hideChat"></i>
        </div>
      </div>
      <iframe :src="chatIframeUrl" frameborder="0" id="c-logistics-iframe"></iframe>
      <div id="shb-chat-IframeMask"></div>
    </div>
    <!-- 悬浮球 -->
    <div 
      v-show="isZoomOutMode" 
      class="floatBtn-wrap" 
      :class="{ hide: !isShowButton}" 
      @click="setZoomOut(false)" 
      @mouseover.stop.prevent="mouseoverCallback"
      @mouseout.stop.prevent="mouseoutCallback"
      >
      <i class="iconfont icon-zaixiankefu"></i>
    </div>
  </div>
</template>

<script>
/** api */
import { getTenantUserSponsorInfo } from '@src/api/ImApi.js'
/** util */
import { isDevelopment } from '@src/util/platform';
export default {
  name: 'OnlineChatModal',
  data () {
    return {
      show:true,
      chatIframeUrl:'',
      isLoadEed:false,
      showRedirect:false,
      isZoomOutMode: false, // 缩小模式
      isShowButton:false, // 是否全部显示icon图标
      timer:null,
    }
  },
  created(){
    this.$eventBus.$on('im-customerService-open-chat', this.openChat);
  },
  destroyed () {
    this.$eventBus.$off('im-customerService-open-chat', this.openChat);
  },
  mounted(){
    window.addEventListener('message', (e)=>{
      // 监听子页面在线客服发来的消息用于消息提升(c端门户)
      if(e.data.type=='im-customerService' && (!this.show || this.isZoomOutMode)){
        this.$eventBus.$emit('socket-addMessage', { notifyType: 'im-customerService' })
      }
      // 监听子页面url发生变化(c端门户)
      if(e.data.type=='c-im-url-change'){
        this.showRedirect = true
      }
      // 监听子页面 vue-route 发生变化(c端门户)
      if(e.data.type=='c-im-isImPage'){
        if(!e.data.value){
          this.showRedirect = true
        }
      }
      // 门户在线客服询问是否读取消息
      if(e.data.type=='c-im-onReceivedMessage'){
        if(this.show && !this.isZoomOutMode){
          // 如果显示聊天页面则读取消息
          this.receivedMessage()
        }
      }
    }, false);
    
    this.getSponsorInfo()
  },
  watch:{
    show(value){
      if(this.isLoadEed && value){
        this.receivedMessage()
      }
      this.isZoomOutMode = false
      if(this.timer) clearTimeout(this.timer)
    },
    isZoomOutMode(value) {
      if(value){        
        this.isShowButton = true
        this.hideButton()
      }else{
        if(this.timer) clearTimeout(this.timer)
        this.receivedMessage()
      }
    }
  },
  methods: {
    receivedMessage() {
      let iframe = this.getIframeDom()
      iframe.contentWindow.postMessage({type:'im-onReceivedMessage-true'},'*')
    },
    getIframeDom(){
      return document.getElementById('c-logistics-iframe')
    },
    hideChat(){
      this.show = false
    },
    openChat(){
      this.show = true
      this.isZoomOutMode = false
    },
    async getSponsorInfo() {
      try {
        const { code, data, message } = await getTenantUserSponsorInfo()
        if (code == 0) {
          let sponsorInfo = JSON.stringify(data)
          this.chatIframeUrl = `${this.getUrl()}?from=SDK&customerService=1&sponsorInfo=${sponsorInfo}&onReceivedMessage=1`
          this.getIframeDom().onload = () => {
            this.isLoadEed = true
          }
        } else {
          this.$message.error(message)
          this.isLoadEed = true
        }
      } catch (error) {
        this.isLoadEed = true
      }
    },
    getUrl() {
      let isDev = isDevelopment()
      let host = ''
      let url = ''
      let domainId = '102308' // 测试，预发 C端domainId

      if (isDev) {
        host = 'http://127.0.0.1:8080'
      } else {
        if (window.location.host.includes('cloud.shb.ltd')) {
          // 独立端也是加载钉钉端
          host = 'shb3144.eapps.dingtalkcloud.com'
        } else {
          host = window.location.host
        }
      }
      
      if (host == 'app.shb.ltd' || host == 'shb3144.eapps.dingtalkcloud.com') {
        domainId = 102389 // 102389CSM线上专用domainId  102308测试环境用
      }
      
      url = isDev ? `${host}/#/chat` : `${window.location.protocol}//${host}/lianke-h5/${domainId}#/chat`

      return url
    },
    iframeReload(){
      let iframe = this.getIframeDom()
      iframe.contentWindow.postMessage({type:'im-reload-page'},'*')
      setTimeout(() => {
        // 页面刷新默认隐藏回退按钮
        this.showRedirect = false
      }, 1000);
    },
    redirect(){
      // 强制返回在线客服聊天页面
      let iframe = this.getIframeDom()
      iframe.src = this.chatIframeUrl
      this.showRedirect = false
    },
    setZoomOut(value) {
      this.isZoomOutMode = value;
    },
    hideButton(){
      if(this.timer) clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.isShowButton = false
      }, 15 * 1000);
    },
    mouseoverCallback(){
      this.isShowButton = true
      if(this.timer) clearTimeout(this.timer)
    },
    mouseoutCallback(){
      this.hideButton()
    },
    zoomHoverBall(e) {
      this.setZoomOut(true)
      const dom = document.querySelector('.floatBtn-wrap')
      const { clientX, clientY } = e
      const cw = document.body.clientWidth
      const ch = document.body.clientHeight
      const duration = 0.4
      const rules = `
        @keyframes imZoomOut {
          0% {
            right:${cw - clientX}px;
            bottom:${ch - clientY}px;
            transform: scale(0);
          }
          100% {
            right:12px;
            bottom:16px;
            transform: scale(1);
          }
        }`
      const style = document.createElement("style")
      style.setAttribute("type", "text/css")
      document.head.appendChild(style)
      const sheet = style.sheet
      sheet.insertRule(rules, 0)
      dom.style.animation = `imZoomOut ${duration}s ease 0s`
      setTimeout(() => {
        dom.style.animation = "none"
        style.remove()
      }, duration * 1000)
    },
  }
}
</script>

<style scoped lang='scss'>
.shb-chat {
  position: fixed;
  z-index: 999999;
  left: 50%;
  top: 50%;
  // transform: translate(-50%, -50%);
  width: 600px;
  height: 555px;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 8px 40px 0 rgb(0 0 0 / 20%);
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  background-color: #fafafa;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 56px;
    box-sizing: border-box;
    padding: 0 24px;
    background: #fafafa;

    .title {
      font-size: 16px;
      font-weight: bold;
      color: #262626;
    }
    .icon-box{
      display: flex;
      justify-content: center;
      align-items: center;
      .iconfont {
        font-size: 20px;
        cursor: pointer;
        color: #8C8C8C;
        margin-left: 16px;
        &.icon-arrow-left{
          font-size: 16px;
        }
      }
    }
  }

  iframe {
    flex: 1;
  }
}
.floatBtn-wrap{
  position: fixed;
  z-index: 99999;
  right: 12px;
  bottom: 16px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.5s;
  background:$color-primary-light-6;
  .icon-zaixiankefu {
    color: #ffffff;
    font-size: 20px;
  }
  &:hover {
    box-shadow:0px 2px 8px 0px $color-primary-light-1;
  }
  &.hide {
    right: -20px;
    opacity: 0.45;
  }
}
</style>